#include "communicate1.h"
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <cstring>

#include "cJSON.h"

#define BUFFSIZE 1024

void communicate1(){
    cJSON *one=NULL;
    one=cJSON_CreateObject();
    cJSON_AddNumberToObject(one,"code",1);
    cJSON_AddStringToObject(one,"name","root");
    cJSON_AddStringToObject(one,"password","123456");

    int client_sockfd = 0;
    int len = 0;
    struct sockaddr_in server_addr;
    socklen_t sin_size = 0;
    char *buf= NULL;
    buf=cJSON_Print(one);
    bzero(&server_addr, sizeof(struct sockaddr_in));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr("192.168.141.128");
    server_addr.sin_port = htons(9090);

    if((client_sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
        perror("socket error!\n");
    }

    sin_size = sizeof(struct sockaddr_in);

    if((len = sendto(client_sockfd, buf, strlen(buf), 0 ,(struct sockaddr*)&server_addr, sizeof(struct sockaddr))) < 0)
    {
        perror("sendto fail!\n");
    }
    char *buf2=NULL;
    if((len = recvfrom(client_sockfd,buf2 , BUFFSIZE, 0, (struct sockaddr*)&server_addr, &sin_size)) < 0)
    {
        perror("recvfrom error!\n");
    }else{
        cJSON *token=NULL;
        cJSON *two=NULL;
        two= cJSON_Parse(buf2);
        token= cJSON_GetObjectItem(two,"token");
        //到时候这里定义全局变量
        char *token_buf=NULL;
        token_buf=token->valuestring;

    }
    close(client_sockfd);

    cJSON_Delete(one);
    //用消息队列发令牌给collect_data
}